import { getToken, loginOut } from "@/utils/token";
import Taro, {
  RequestTask,
  showToast,
  showLoading,
  hideLoading,
} from "@tarojs/taro";
import config from "../../config/api.self";

const { ApiRoot } = config;

const baseUrl = ApiRoot["develop"];

// 未处理请求
const pendding = new Set<RequestTask<any>>();

// 自定义参数
interface CustomRequestOption extends Taro.request.Option {
  mask?: boolean;
}

export const request = <T>(option: CustomRequestOption): Promise<T> => {
  return new Promise((resolve, reject) => {
    option.mask !== false && showLoading({ title: "加载中" });
    let header = {};
    if (
      ~option.url.indexOf("/user/password") ||
      ~option.url.indexOf("/user/login")
    ) {
      header = {
        ...option.header,
      };
    } else {
      header = {
        Authorization: getToken() || "",
        ...option.header,
      };
    }

    const responseHandle = (res) => {
      const { data, code } = res?.data || {};
      switch (code) {
        case 200:
          return () => {
            resolve(data);
            option.success?.(res);
          };
        case 777:
          return () => {
            reject();
            loginOut();
          };
        default:
          return () => {
            reject();
          };
      }
    };

    const http = Taro.request<API.ResponseResult<T>>({
      ...option,
      url: baseUrl + "/household_supplies" + option.url,
      header,
      success(res) {
        responseHandle(res)();
      },
      fail: (...res) => {
        reject(...res);
        option.fail?.(...res);
      },
      complete(res: any) {
        const { code, message } = res?.data || {};
        const success = code === 200;
        pendding.size <= 1 && hideLoading();
        pendding.delete(http);
        option.complete?.(res);
        // 提示信息是否弹出判断
        !option.fail &&
          (success || showToast({ title: message, icon: "none" }));
      },
    });
    pendding.add(http);
  });
};
